<template>
  <div class="course-video">
    <el-card>
      <div slot="header">
        <span>课程</span>
        <br />
        <span>阶段</span>
        <br />
        <span>课时</span>
      </div>
      <el-form label-width="70px">
        <el-form-item label="视频上传">
          <input ref="video-file" type="file" />
        </el-form-item>
        <el-form-item label="封面上传">
          <input ref="image-file" type="file" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleUpload">开始上传</el-button>
          <el-button @click="$router.back()">返回</el-button>
        </el-form-item>
        <el-form-item>
          <p>视频上传中：{{ uploadPercent }}%</p>
          <p v-if="isUploadSuccess">视频转码中： {{ isTransCodeSuccess ? '完成' : '正在转码，请稍后' }}</p>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
import {
  aliyunImagUploadAddressAdnAuth,
  aliyunVideoUploadAddressAdnAuth,
  transCodeVideo,
  getAliyunTransCodePercent
} from '@/services/aliyun-oss'

export default Vue.extend({
  name: 'CourseVideo',
  props: {
    courseId: {
      type: [String, Number],
      required: true
    }
  },
  data () {
    return {
      uploader: null,
      imageUrl: '',
      videoId: null,
      uploadPercent: 0,
      isUploadSuccess: false,
      isTransCodeSuccess: false
    }
  },
  computed: {
    video () {
      return (this as any).$refs['video-file']
    },
    image () {
      return (this as any).$refs['image-file']
    }
  },
  created () {
    (this as any).initUploader()
  },
  methods: {
    initUploader () {
      (this as any).uploader = new window.AliyunUpload.Vod({
        // 阿里账号ID，必须有值
        userId: 1618139964448548,
        // 上传到视频点播的地域，默认值为'cn-shanghai'，//eu-central-1，ap-southeast-1
        region: '',
        // 分片大小默认1 MB，不能小于100 KB
        partSize: 1048576,
        // 并行上传分片个数，默认5
        parallel: 5,
        // 网络原因失败时，重新上传次数，默认为3
        retryCount: 3,
        // 网络原因失败时，重新上传间隔时间，默认为2秒
        retryDuration: 2,
        // 开始上传
        onUploadstarted: async (uploadInfo: any) => {
          const _this = this as any
          // 1.通过我们的后端获取文件上传凭证
          let uploadAddressAndAuth
          if (uploadInfo.isImage) {
            // 获取图片上传凭证
            const { data } = await aliyunImagUploadAddressAdnAuth()
            uploadAddressAndAuth = data.data
            _this.imageUrl = data.data.imageURL
          } else {
            // 获取视频上传凭证
            const { data } = await aliyunVideoUploadAddressAdnAuth({
              fileName: uploadInfo.file.name,
              imageUrl: _this.imageUrl // 请确保一定是先上传图片以获取imageURL
            })
            uploadAddressAndAuth = data.data
            _this.videoId = uploadAddressAndAuth.videoId
          }
          // 2.调用uploader.setUploadAuthAndAddress设置上传凭证
          ;(_this.uploader as any).setUploadAuthAndAddress(
            uploadInfo,
            uploadAddressAndAuth.uploadAuth,
            uploadAddressAndAuth.uploadAddress,
            uploadAddressAndAuth.imageId || uploadAddressAndAuth.videoId
          )
          // 3.设置好上传凭证确认没有问题，上传进度开始
          // uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress,videoId);
        },
        // 文件上传成功
        onUploadSucceed: function (uploadInfo: any) {
          console.log('onUploadSucceed')
        },
        // 文件上传失败
        onUploadFailed: function (uploadInfo: any, code: any, message: any) {
          console.log('onUploadFailed')
        },
        // 文件上传进度，单位：字节
        onUploadProgress: (uploadInfo: any, totalSize: any, loadedPercent: any) => {
          console.log('onUploadProgress')
          const _this = this as any
          if (!uploadInfo.isImage) {
            _this.uploadPercent = Math.floor(loadedPercent * 100)
          }
        },
        // 上传凭证或STS token超时
        onUploadTokenExpired: function (uploadInfo: any) {
          console.log('onUploadTokenExpired')
        },
        // 全部文件上传结束
        onUploadEnd: async (uploadInfo: any) => {
          const _this = this as any
          _this.isUploadSuccess = true
          // 请求转码
          const { data } = await transCodeVideo({
            lessonId: _this.$route.query.lessonId,
            coverImageUrl: _this.imageURL,
            fileName: (_this.video as any).files[0].name,
            fileId: _this.videoId
          })

          // 轮询查询转码进度
          const timer = setInterval(async () => {
            const { data } = await getAliyunTransCodePercent(_this.$route.query.lessonId)
            if (data.data === 100) {
              _this.isTransCodeSuccess = true
              window.clearInterval(timer)
              console.log('转码成功')
            }
          }, 3000)
        }
      })
    },
    handleUpload () {
      const _this = this as any
      // 初始化上传状态
      _this.isUploadSuccess = false
      _this.isTransCodeSuccess = false
      _this.uploadPercent = 0

      // 获取上传的文件
      const videoFile = _this.video.files[0]
      const imageFile = _this.image.files[0]
      const uploader = _this.uploader as any

      // 将用户所选的文件添加到上传列表中
      // 一旦开始上传，它就会按照列表中添加的顺序开始上传
      uploader.addFile(imageFile, null, null, null, '{"Vod":{}}')
      uploader.addFile(videoFile, null, null, null, '{"Vod":{}}')

      // 开始上传，触发onUploadstarted事件
      uploader.startUpload()
    }
  }
})
</script>

<style scoped lang="scss"></style>
